package com.duodao.common.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.http.HttpRequest;

public class LoginFilter implements Filter {

	public FilterConfig config;
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		this.config = filterConfig;
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest hRequest = (HttpServletRequest)request;
		String loginPage = config.getInitParameter("logonStrings");
		String loginPath = hRequest.getContextPath()+config.getInitParameter("logonStrings");
		HttpSession session = hRequest.getSession();
		if (isContains(hRequest.getRequestURI(),loginPage.split(";"))) {
			chain.doFilter(request, response);
			return;
		}
		if (session.getAttribute("ACCOUNTNO")!=null&&session.getAttribute("loginName")!="") {
			chain.doFilter(request, response);
			return;
		}else{
			request.getRequestDispatcher(loginPath).forward(request, response);
			chain.doFilter(request, response);
			return;
		}

	}

	@Override
	public void destroy() {
		this.config = null;
	}
	
	private boolean isContains(String container,String[] regex){
		boolean result = false;
		for (int i = 0; i < regex.length; i++) {
			if(container.indexOf(regex[i])!=-1){
				return true;
			}
		}	
		return result;
	}

}
